<?php

// 查立得PHP+mysql通用预约排队系统 V2024.12.12
// 演示地址: http://duilie.chalide.cn
// 文件路径: hexiao.php
// 文件大小: 28412 字节
// 最后修改时间: 2024-12-17 21:00:00
// 作者: yujianyue
// 邮件: 15058593138@qq.com
// 版权所有,保留发行权和署名权
define('IN_SYSTEM', true);
require_once 'inc/conn.php';
require_once 'inc/pubs.php';
require_once 'inc/json.php';

session_start();

// 检查登录状态，未登录跳转到登录页
if(!isset($_SESSION['doctor'])) {
    header('Location: login.php');
    exit;
}

// 处理AJAX请求
if(isset($_GET['act'])) {
    switch($_GET['act']) {
        case 'logout':
            doLogout();
            break;
        case 'waiting':
            getWaitingList();
            break;
        case 'verified':
            getVerifiedList();
            break;
        case 'stats':
            getStats();
            break;
        case 'verify':
            doVerify();
            break;
        case 'setting':
            saveSetting();
            break;
        case 'password':
            changePassword();
            break;
        case 'isyue':
            isyue();
            break;
        default:
            json_msg(0, '未知操作');
    }
    exit;
}

// 退出登录
function doLogout() {
    unset($_SESSION['doctor']);
    header('Location: login.php');
    exit;
}

// 获取未核销列表
function getWaitingList() {
    global $conn;
    
    $doctor = $_SESSION['doctor'];
    $today = date('Y-m-d');
    
    $sql = "SELECT id, patient_name, sequence, verify_code, create_time 
            FROM booking 
            WHERE doctor_id = {$doctor['id']} 
            AND booking_date = '$today' 
            AND status = 0 
            ORDER BY sequence ASC";
            
    $result = $conn->query($sql);
    $list = array();
    
    while($row = $result->fetch_assoc()) {
        // 姓名显示首尾字
        $name = mb_substr($row['patient_name'], 0, 1) . '*' . 
                mb_substr($row['patient_name'], -1);
                
        $list[] = array(
            'id' => $row['id'],
            'name' => $name,
            'sequence' => $row['sequence'],
            'verify_code' => $row['verify_code'],
            'time' => $row['create_time']
        );
    }
    
    json_msg(1, 'success', $list);
}

// 获取已核销列表
function getVerifiedList() {
    global $conn;
    
    $doctor = $_SESSION['doctor'];
    $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
    $limit = 10;
    $offset = ($page - 1) * $limit;
    $search = isset($_GET['search']) ? safe_string($_GET['search']) : '';
    
    $where = "doctor_id = {$doctor['id']} AND status = 1";
    if($search) {
        $where .= " AND (patient_name LIKE '%$search%' 
                   OR mobile LIKE '%$search%' 
                   OR sequence LIKE '%$search%')";
    }
    
    // 获取总数
    $sql = "SELECT COUNT(*) as total FROM booking WHERE $where";
    $total = $conn->query($sql)->fetch_assoc()['total'];
    
    // 获取当页数据
    $sql = "SELECT * FROM booking 
            WHERE $where 
            ORDER BY verify_time DESC 
            LIMIT $offset, $limit";
    $result = $conn->query($sql);
    
    $list = array();
    while($row = $result->fetch_assoc()) {
        $list[] = array(
            'sequence' => $row['sequence'],
            'name' => $row['patient_name'],
            'mobile' => substr_replace($row['mobile'], '****', 3, 4),
            'verify_time' => $row['verify_time']
        );
    }
    
    json_msg(1, 'success', array(
        'list' => $list,
        'total' => $total,
        'page' => $page,
        'pages' => ceil($total / $limit)
    ));
}

// 获取统计信息
function getStats() {
    global $conn;
    
    $doctor = $_SESSION['doctor'];
    $today = date('Y-m-d');
    
    // 获取今日统计
    $sql = "SELECT 
            SUM(status = 0) as waiting,
            SUM(status = 1) as verified
            FROM booking 
            WHERE doctor_id = {$doctor['id']} 
            AND booking_date = '$today'";
    $today_stats = $conn->query($sql)->fetch_assoc();
    
    // 获取每日统计
    $sql = "SELECT 
            booking_date,
            SUM(status = 0) as waiting,
            SUM(status = 1) as verified
            FROM booking 
            WHERE doctor_id = {$doctor['id']}
            GROUP BY booking_date 
            ORDER BY booking_date DESC 
            LIMIT 30";
    $result = $conn->query($sql);
    
    $daily_stats = array();
    while($row = $result->fetch_assoc()) {
        $daily_stats[] = $row;
    }
    
    json_msg(1, 'success', array(
        'today' => $today_stats,
        'daily' => $daily_stats
    ));
}


// 刷新二维码
function isyue() {
    global $CONFIG;
    global $conn;
$docid = $_SESSION['doctor']['id'];
$sql = "SELECT id, name, department, status, end_time FROM doctor WHERE id = $docid";
$doctor = $conn->query($sql)->fetch_assoc();    
    // 检查医生状态
    if($doctor['status'] != 1) {
        json_msg(0, '暂停预约');
    }
    
    // 检查结束时间
    if($doctor['end_time'] && strtotime($doctor['end_time']) < time()) {
        json_msg(0, '已结束预约');
    }
    
        json_msg(0, '预约中');
}
// 核销处理
function doVerify() {
    global $conn;
    
    $doctor = $_SESSION['doctor'];
    $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
    $code = isset($_POST['code']) ? safe_string($_POST['code']) : '';
    
    if(!$id || !$code) {
        json_msg(0, '参数错误');
    }
    
    // 验证核销码
    $sql = "SELECT * FROM booking 
            WHERE id = $id 
            AND doctor_id = {$doctor['id']}
            AND verify_code = '$code'
            AND status = 0";
    $booking = $conn->query($sql)->fetch_assoc();
    
    if(!$booking) {
        json_msg(0, '核销码错误或已被核销');
    }
    
    // 更新状态
    $sql = "UPDATE booking 
            SET status = 1, verify_time = NOW() 
            WHERE id = $id";
    if($conn->query($sql)) {
        json_msg(1, '核销成功');
    } else {
        json_msg(0, '系统错误，请重试');
    }
}

// 保存设置
function saveSetting() {
    global $conn;
    
    $doctor = $_SESSION['doctor'];
    $status = isset($_POST['status']) ? intval($_POST['status']) : 0;
    $end_time = isset($_POST['end_time']) ? safe_string($_POST['end_time']) : '';
    
    if($status == 1 && !strtotime($end_time)) {
        json_msg(0, '请设置有效的结束时间');
    }
    
    $sql = "UPDATE doctor 
            SET status = $status, 
            end_time = " . ($end_time ? "'$end_time'" : "NULL") . "
            WHERE id = {$doctor['id']}";
            
    if($conn->query($sql)) {
        json_msg(1, '设置已保存');
    } else {
        json_msg(0, '保存失败，请重试');
    }
}

// 修改密码
function changePassword() {
    global $conn;
    
    $doctor = $_SESSION['doctor'];
    $old_pwd = isset($_POST['old_pwd']) ? safe_string($_POST['old_pwd']) : '';
    $new_pwd = isset($_POST['new_pwd']) ? safe_string($_POST['new_pwd']) : '';
    $confirm_pwd = isset($_POST['confirm_pwd']) ? safe_string($_POST['confirm_pwd']) : '';
    
    if(empty($old_pwd) || empty($new_pwd) || empty($confirm_pwd)) {
        json_msg(0, '请填写完整');
    }
    
    if(!preg_match('/^[a-zA-Z0-9]{6,16}$/', $new_pwd)) {
        json_msg(0, '新密码必须为6-16位数字字母');
    }
    
    if($new_pwd !== $confirm_pwd) {
        json_msg(0, '两次输入的新密码不一致');
    }
    
    // 验证旧密码
    $old_pwd = md5($old_pwd);
    $sql = "SELECT id FROM doctor 
            WHERE id = {$doctor['id']} 
            AND password = '$old_pwd'";
    if(!$conn->query($sql)->fetch_assoc()) {
        json_msg(0, '旧密码错误');
    }
    
    // 更新密码
    $new_pwd = md5($new_pwd);
    $sql = "UPDATE doctor 
            SET password = '$new_pwd' 
            WHERE id = {$doctor['id']}";
            
    if($conn->query($sql)) {
        json_msg(1, '密码修改成功，请重新登录');
    } else {
        json_msg(0, '修改失败，请重试');
    }
}

?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>核销管理 - <?php echo $CONFIG['site_title']; ?></title>
    <script>
        // 将PHP配置传递给JavaScript
        var CONFIG = <?php echo json_encode($CONFIG); ?>;
    </script>
    <style>
        body { 
            font-family: Arial; 
            max-width: 1200px; 
            margin: 0 auto; 
            padding: 20px;
        }
        
        /* 登录表单样式 */
        .login-form {
            max-width: 400px;
            margin: 100px auto;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 4px;
            text-align: center;
        }
        .login-form h2 {
            margin-bottom: 20px;
        }
        
        /* 表单项通用样式 */
        .form-item {
            margin: 15px 0;
        }
        .form-item input {
            width: 100%;
            padding: 8px;
            box-sizing: border-box;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        
        /* 按钮样式 */
        .btn {
            padding: 8px 20px;
            background: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .btn:hover {
            background: #0056b3;
        }
        .btn-logout {
            padding: 5px 15px;
            background: #dc3545;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .btn-logout:hover {
            background: #c82333;
        }
        
        /* 头部样式 */
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .header h1 {
            margin: 0;
        }
        
        /* 标签页样式 */
        .tabs {
            display: flex;
            border-bottom: 1px solid #ddd;
            margin-bottom: 20px;
        }
        .tab {
            padding: 10px 20px;
            cursor: pointer;
            border: 1px solid transparent;
            margin-bottom: -1px;
        }
        .tab:hover {
            background: #f8f9fa;
        }
        .tab.active {
            border: 1px solid #ddd;
            border-bottom-color: white;
            background: white;
        }
        
        /* 内容区域样式 */
        #tab-content {
            min-height: 400px;
            padding: 20px 0;
        }
        
        /* 表格样式 */
        .table {
            width: 100%;
            border-collapse: collapse;
        }
        .table th, .table td {
            padding: 10px;
            border: 1px solid #ddd;
            text-align: left;
        }
        .table th {
            background: #f8f9fa;
        }
        
        /* 搜索框样式 */
        .search-box {
            margin-bottom: 20px;
        }
        .search-box input {
            width: 200px;
            padding: 6px;
            margin-right: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        
        /* 分页样式 */
        .pagination {
            margin-top: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .pagination select {
            margin: 0 10px;
            padding: 5px;
        }
        .pagination button {
            padding: 5px 10px;
            margin: 0 5px;
            border: 1px solid #ddd;
            background: white;
            cursor: pointer;
        }
        .pagination button:disabled {
            background: #f8f9fa;
            cursor: not-allowed;
        }
        
        /* 统计信息样式 */
        .stats-today {
            display: flex;
            justify-content: space-around;
            margin-bottom: 30px;
            text-align: center;
        }
        .stats-today .number {
            font-size: 36px;
            font-weight: bold;
            color: #007bff;
        }
        .stats-today .label {
            color: #666;
        }
        
        /* 设置表单样式 */
        .setting-form {
            max-width: 600px;
        }
        .setting-form .form-item label {
            display: block;
            margin-bottom: 5px;
        }
        
        /* 遮罩层样式 */
        .mask {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .mask-box {
            background: white;
            padding: 20px;
            border-radius: 4px;
            min-width: 300px;
            position: relative;
        }
        .mask-close {
            position: absolute;
            right: 10px;
            top: 10px;
            cursor: pointer;
            font-size: 20px;
        }
        .mask-content {
            margin: 20px 0;
        }
        .mask-buttons {
            text-align: right;
            border-top: 1px solid #eee;
            padding-top: 15px;
        }
    </style>
</head>
<body>
    <div id="main">
        <div class="header">
            <h1>核销管理</h1>
            <span id="topstats"></span>
            <button class="btn-logout" onclick="doLogout()">退出</button>
        </div>
        
        <div class="tabs">
            <div class="tab active" onclick="switchTab(0)">队列列表</div>
            <div class="tab" onclick="switchTab(1)">已核销</div>
            <div class="tab" onclick="switchTab(2)">统计信息</div>
            <div class="tab" onclick="switchTab(3)">设置</div>
            <div class="tab" onclick="switchTab(4)">修改密码</div>
        </div>
        
        <div id="tab-content">
            <!-- 内容将由JavaScript动态加载 -->
        </div>
    </div>

    <script src="inc/js.js"></script>
    <script>
        // 全局变量
        var currentTab = 0;
        var refreshTimer = null;
        var currentPage = 1;
        var searchText = '';

        // 页面加载完成检查登录状态
        window.onload = function() {
            checkLoginStatus();
        };

        // 检查登录状态
        function checkLoginStatus() {
            // 由于已经在PHP中检查了登录状态，这里只需要加载默认标签页
            loadTabContent(0);
        }
       // 退出登录
        function doLogout() {
            window.location.href = '?act=logout';
        }
        // 切换标签页
        function switchTab(index) {
            var tabs = document.getElementsByClassName('tab');
            for(var i = 0; i < tabs.length; i++) {
                tabs[i].className = 'tab' + (i === index ? ' active' : '');
            }
            currentTab = index;
            loadTabContent(index);
        }

        // 加载标签页内容
        function loadTabContent(index) {
            clearInterval(refreshTimer);
            var content = document.getElementById('tab-content');
            
            switch(index) {
                case 0: // 队列列表
                    loadWaitingList();
                    refreshTimer = setInterval(loadWaitingList, 8000);
                    break;
                case 1: // 已核销
                    loadVerifiedList();
                    break;
                case 2: // 统计信息
                    loadStats();
                    break;
                case 3: // 设置
                    loadSettings();
                    break;
                case 4: // 修改密码
                    loadPasswordForm();
                    break;
            }
        }

        // 加载队列列表
        function loadWaitingList() {
            ajax({
                url: 'hexiao.php',
                type: 'GET',
                data: {act: 'waiting'},
                success: function(res) {
                    var data = JSON.parse(res);
                    if(data.code === 1) {
                        var html = '<table class="table">' +
                                  '<tr><th>序号</th><th>姓名</th><th>预约时间</th><th>操作</th></tr>';
                        
                        data.data.forEach(function(item) {
                            html += '<tr>' +
                                   '<td>' + item.sequence + '</td>' +
                                   '<td>' + item.name + '</td>' +
                                   '<td>' + item.time + '</td>' +
                                   '<td><button class="btn" onclick="showVerifyDialog(' + 
                                   item.id + ',\'' + item.name + '\')">核销</button></td>' +
                                   '</tr>';
                        });
                        
                        html += '</table>';
                        document.getElementById('tab-content').innerHTML = html;
                    }
                }
            });
        }

        // 显示核销对话框
        function showVerifyDialog(id, name) {
            var content = '<p>姓名：' + name + '</p>' +
                         '<div class="form-item">' +
                         '<input type="text" id="verify_code" placeholder="请输入核销码">' +
                         '</div>';
                         
            showMask(content, [{
                text: '确定',
                click: function() {
                    var code = document.getElementById('verify_code').value;
                    doVerify(id, code);
                }
            }]);
        }

        // 执行核销
        function doVerify(id, code) {
            ajax({
                url: '?act=verify',
                type: 'POST',
                data: {
                    act: 'verify',
                    id: id,
                    code: code
                },
                success: function(res) {
                    var data = JSON.parse(res);
                    alert(data.msg);
                    if(data.code === 1) {
                        document.body.removeChild(document.querySelector('.mask'));
                        loadWaitingList();
                    }
                }
            });
        }

        // 加载已核销列表
        function loadVerifiedList(page) {
            currentPage = page || currentPage;
            
            var html = '<div class="search-box">' +
                       '<input type="text" id="search" placeholder="搜索" value="' + searchText + '">' +
                       '<button class="btn" onclick="searchVerified()">搜索</button>' +
                       '</div>';
                       
            ajax({
                url: 'hexiao.php',
                type: 'GET',
                data: {
                    act: 'verified',
                    page: currentPage,
                    search: searchText
                },
                success: function(res) {
                    var data = JSON.parse(res);
                    if(data.code === 1) {
                        html += '<table class="table">' +
                               '<tr><th>序号</th><th>姓名</th><th>手机号</th><th>核销时间</th></tr>';
                        
                        data.data.list.forEach(function(item) {
                            html += '<tr>' +
                                   '<td>' + item.sequence + '</td>' +
                                   '<td>' + item.name + '</td>' +
                                   '<td>' + item.mobile + '</td>' +
                                   '<td>' + item.verify_time + '</td>' +
                                   '</tr>';
                        });
                        
                        html += '</table>';
                        
                        // 添加分页
                        if(data.data.total > 0) {
                            html += createPagination(data.data.page, data.data.pages);
                        }
                        
                        document.getElementById('tab-content').innerHTML = html;
                    }
                }
            });
        }

        // 搜索已核销记录
        function searchVerified() {
            searchText = document.getElementById('search').value;
            loadVerifiedList(1);
        }

        // 创建分页HTML
        function createPagination(current, total) {
            var html = '<div class="pagination">';
            
            // 首页
            html += '<button ' + (current == 1 ? 'disabled' : '') + 
                    ' onclick="loadVerifiedList(1)">首页</button>';
            
            // 上一页
            html += '<button ' + (current == 1 ? 'disabled' : '') + 
                    ' onclick="loadVerifiedList(' + (current - 1) + ')">上一页</button>';
            
            // 页码选择
            html += '<select onchange="loadVerifiedList(this.value)">';
            for(var i = 1; i <= total; i++) {
                html += '<option value="' + i + '"' + (i == current ? ' selected' : '') + 
                        '>第' + i + '页</option>';
            }
            html += '</select>';
            
            // 下一页
            html += '<button ' + (current == total ? 'disabled' : '') + 
                    ' onclick="loadVerifiedList(' + (current + 1) + ')">下一页</button>';
            
            // 末页
            html += '<button ' + (current == total ? 'disabled' : '') + 
                    ' onclick="loadVerifiedList(' + total + ')">末页</button>';
                    
            html += '</div>';
            return html;
        }

        // 加载统计信息
        function loadStats() {
            ajax({
                url: 'hexiao.php',
                type: 'GET',
                data: {act: 'stats'},
                success: function(res) {
                    var data = JSON.parse(res);
                    if(data.code === 1) {
                        var html = '<div class="stats-today">' +
                                  '<div><div class="number">' + data.data.today.waiting + '</div>' +
                                  '<div class="label">待核销</div></div>' +
                                  '<div><div class="number">' + data.data.today.verified + '</div>' +
                                  '<div class="label">已核销</div></div>' +
                                  '</div>';
                        
                        html += '<table class="table">' +
                                '<tr><th>日期</th><th>待核销</th><th>已核销</th></tr>';
                        
                        data.data.daily.forEach(function(item) {
                            html += '<tr>' +
                                   '<td>' + item.booking_date + '</td>' +
                                   '<td>' + item.waiting + '</td>' +
                                   '<td>' + item.verified + '</td>' +
                                   '</tr>';
                        });
                        
                        html += '</table>';
                        document.getElementById('tab-content').innerHTML = html;
                    }
                }
            });
        }

        // 加载设置页面
        function loadSettings() {
            var html = '<div class="setting-form">' +
                       '<div class="form-item">' +
                       '<label>预约状态</label>' +
                       '<select id="status">' +
                       '<option value="0">关闭</option>' +
                       '<option value="1">开启</option>' +
                       '</select>' +
                       '</div>' +
                       '<div class="form-item">' +
                       '<label>结束时间</label>' +
                       '<input type="datetime-local" id="end_time">' +
                       '</div>' +
                       '<button class="btn" onclick="saveSettings()">保存</button>' +
                       '</div>';
                       
            document.getElementById('tab-content').innerHTML = html;
        }

        // 保存设置
        function saveSettings() {
            var status = document.getElementById('status').value;
            var end_time = document.getElementById('end_time').value;
            
            ajax({
                url: '?act=setting',
                type: 'POST',
                data: {
                    act: 'setting',
                    status: status,
                    end_time: end_time
                },
                success: function(res) {
                    var data = JSON.parse(res);
                    alert(data.msg);
                }
            });
        }

        // 加载修改密码表单
        function loadPasswordForm() {
            var html = '<div class="setting-form">' +
                       '<div class="form-item">' +
                       '<label>旧密码</label>' +
                       '<input type="password" id="old_pwd">' +
                       '</div>' +
                       '<div class="form-item">' +
                       '<label>新密码</label>' +
                       '<input type="password" id="new_pwd">' +
                       '</div>' +
                       '<div class="form-item">' +
                       '<label>确认新密码</label>' +
                       '<input type="password" id="confirm_pwd">' +
                       '</div>' +
                       '<button class="btn" onclick="changePassword()">修改</button>' +
                       '</div>';
                       
            document.getElementById('tab-content').innerHTML = html;
        }

        // 修改密码
        function changePassword() {
            var old_pwd = document.getElementById('old_pwd').value;
            var new_pwd = document.getElementById('new_pwd').value;
            var confirm_pwd = document.getElementById('confirm_pwd').value;
            
            ajax({
                url: '?act=password',
                type: 'POST',
                data: {
                    act: 'password',
                    old_pwd: old_pwd,
                    new_pwd: new_pwd,
                    confirm_pwd: confirm_pwd
                },
                success: function(res) {
                    var data = JSON.parse(res);
                    alert(data.msg);
                    if(data.code === 1) {
                        location.reload();
                    }
                }
            });
        }

       function isyue() {
            ajax({
                url: '?act=isyue&',
                type: 'GET',
                success: function(res) {
                    var data = JSON.parse(res);
                    if(data.code === 1) {                      
                         document.getElementById('topstats').innerHTML = 
                            '<div class="sucsess">' + data.msg + '</div>';
                    } else {
                        document.getElementById('topstats').innerHTML = 
                            '<div class="error">' + data.msg + '</div>';
                    }
                }
            });
        }
        isyue();
        setInterval(isyue, <?php echo $CONFIG['qrcode_refresh'] * 1000; ?>);
    </script>
</body>
</html> 